/*
 * Description: 群成员信息
 * Author: wangyifei
 * DateCreated: 2024-06-11 09:20
 */

import { memo, useEffect, useRef, useState } from 'react';
import { Avatar, Button, Divider, Modal, message } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import {
	selectMembersList,
	quitGroupMembers,
	insertMembersItem,
	deleteMembersItem,
	type MembersParam,
	type MembersRes
} from '../../http/chatting-group-members';
import { deleteGroupItem } from '../../http/chatting-group';
import { MembersStyle } from './style';
import { serverURL, userInfo } from '../../config';
import SelectUser, { type SelectUserRef } from './SelectUser';
import DeleteUser, { type DeleteUserRef } from './DeleteUser';
import type { GroupRes } from '../../http/chatting-group';

type MembersProps = {
	open: boolean;
	groupInfo: GroupRes;
	onClose: () => void;
	refreshGroupList: () => void;
	onDelGroup: () => void;
};
const Members = memo((props: MembersProps) => {
	const { open, groupInfo, onClose, refreshGroupList, onDelGroup } = props;

	// 现有群成员
	const [membersList, setMembersList] = useState<MembersRes[]>([]);
	// 是否在群中
	const [currentUser, setCurrentUser] = useState<MembersRes>();
	// 添加群员窗口信息
	const [addOpen, setAddOpen] = useState(false);
	const AddModal = useRef<SelectUserRef>();
	// 移出群员窗口信息
	const [delOpen, setDelOpen] = useState(false);
	const DelModal = useRef<DeleteUserRef>();

	// 查询群成员
	const queryMembersList = async () => {
		const { data } = await selectMembersList({ groupId: groupInfo.id });
		setMembersList(data);
		const find = data.find((item) => item.userId === userInfo.id);
		if (find) {
			setCurrentUser(find);
		}
	};
	useEffect(() => {
		if (open) {
			queryMembersList();
		}
		return () => {
			setMembersList([]);
		};
	}, [open]);

	// 删除群聊
	const delGroupItem = () => {
		Modal.confirm({
			title: '是否确认删除群聊？',
			centered: true,
			onOk: async () => {
				await deleteGroupItem([groupInfo.id]);
				message.success('已删除群聊');
				onDelGroup();
				onClose();
				refreshGroupList();
			}
		});
	};

	// 退出群聊
	const quitGroup = () => {
		Modal.confirm({
			title: '是否确认退出群聊？',
			centered: true,
			onOk: async () => {
				await quitGroupMembers({ groupId: groupInfo.id });
				message.success('已退出群聊');
				onClose();
				refreshGroupList();
			}
		});
	};

	// 添加群成员
	const handleAddUsers = async () => {
		const list = AddModal.current.selectedUsers.map<MembersParam>((item) => ({
			userId: item.id,
			avatar: item.avatar,
			groupId: groupInfo.id,
			nickName: item.realname
		}));
		await insertMembersItem(list);
		queryMembersList();
		message.success('已添加群成员');
		setAddOpen(false);
	};

	// 删除群成员
	const handleDelUsers = async () => {
		const ids = DelModal.current.selectedUsers.map<number>((item) => item.id);
		await deleteMembersItem(ids);
		queryMembersList();
		message.success('已移出群成员');
		setDelOpen(false);
	};

	return (
		<MembersStyle>
			<div className="members_list">
				{membersList.map((item) => (
					<div key={item.id} className="item_info">
						<Avatar
							className="item_avatar"
							shape="square"
							size={35}
							src={serverURL + item.avatar}
						/>
						<div className="item_name">{item.nickName}</div>
					</div>
				))}
				{groupInfo?.groupType === 1 && currentUser?.isAdmin && (
					<>
						<div className="item_info">
							<div className="item_plus_del" onClick={() => setAddOpen(true)}>
								<PlusOutlined />
							</div>
							<div className="item_name">添加</div>
						</div>
						<div className="item_info">
							<div className="item_plus_del" onClick={() => setDelOpen(true)}>
								<MinusOutlined />
							</div>
							<div className="item_name">移出</div>
						</div>
					</>
				)}
			</div>
			{currentUser ? (
				<>
					<Divider />
					<div className="handle_group">
						{currentUser?.isAdmin === 1 ? (
							<Button type="link" danger onClick={delGroupItem}>
								删除群聊
							</Button>
						) : (
							<Button type="link" danger onClick={quitGroup}>
								退出群聊
							</Button>
						)}
					</div>
				</>
			) : null}

			<Modal
				title="添加成员"
				centered
				destroyOnClose
				width={600}
				maskClosable={false}
				open={addOpen}
				onCancel={() => setAddOpen(false)}
				onOk={handleAddUsers}
			>
				<SelectUser membersList={membersList} comRef={AddModal} />
			</Modal>
			<Modal
				title="移出成员"
				centered
				destroyOnClose
				width={600}
				maskClosable={false}
				open={delOpen}
				onCancel={() => setDelOpen(false)}
				onOk={handleDelUsers}
			>
				<DeleteUser membersList={membersList} comRef={DelModal} />
			</Modal>
		</MembersStyle>
	);
});

export default Members;
